package com.zijiebutiao.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.builder.ExcelWriterBuilder;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.zijiebutiao.service.BusinessService;
import com.zijiebutiao.utils.ResultVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import net.sf.jasperreports.engine.*;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Date 2023/3/3 19:48
 * @Author 时间刺客
 */
@Transactional(rollbackFor = Exception.class)
@RestController
@RequestMapping("/report")
@Api(tags = "运营数据统计")
public class BusinessController {
    @Autowired
    private BusinessService businessService;


    @ApiOperation(value = "获取运营数据",notes = "",response = ResultVo.class)
    @GetMapping("/getBusinessReportData")
    public ResultVo getBusinessReportData() throws InterruptedException {
        Map<String,Object> map=businessService.getData();
        map.put("hotSetmeal",businessService.getDataList());
        return ResultVo.success(map);
    }

    /**
     * 导出excel
     * @return
     * @throws InterruptedException
     */
    @ApiOperation(value = "导出excel",notes = "",response = ResultVo.class)
    @GetMapping("/exportBusinessReport")
    public void exportBusinessReport(HttpServletResponse resp, HttpServletRequest res) throws InterruptedException, IOException {
          Map<String,Object> data=businessService.getData();
          List list = businessService.getDataList();
          String dirpath="D:\\demo\\dow";
          String filename= UUID.randomUUID().toString().replaceAll("-","")+".xlsx";
          File file=new File(dirpath,filename);

          ExcelWriterBuilder excelWriterBuilder = EasyExcel.write(file).withTemplate("D:\\demo\\tel\\report_template.xlsx");
          WriteSheet sheet = excelWriterBuilder.sheet().build();
          ExcelWriter excelWriter = excelWriterBuilder.build();

          excelWriter.fill(data,sheet);
          excelWriter.fill(list,sheet);

          excelWriter.finish();


        String mimeType = res.getServletContext().getMimeType(filename);
        resp.setHeader("content-type",mimeType);
        resp.setHeader("Access-Control-Expose-Headers","content-disposition");
        resp.setHeader("content-disposition","attachment;filename="+filename);

        FileInputStream fileInputStream = new FileInputStream(file);
        ServletOutputStream outputStream = resp.getOutputStream();

        int len=-1;
        byte[] bytes=new byte[1024];
        while ((len=fileInputStream.read(bytes))!=-1){
            outputStream.write(bytes,0,len);
        }

        fileInputStream.close();
    }

    /**
     * 导出pdf
     * @throws InterruptedException
     * @throws JRException
     */
    @ApiOperation(value = "导出pdf",notes = "",response = ResultVo.class)
    @GetMapping("exportBusinessReport4PDF")
    public void exportBusinessReport4PDF(HttpServletRequest res,HttpServletResponse resp) throws InterruptedException, JRException, IOException {
//        Map<String,Object> data=businessService.getData();
//        data.put("msg","test msg...");
//
//        String telPath="D:\\demo\\tel\\test.jrxml";
//        String jasperDatapath="D:\\demo\\tel\\test.jasper";
//
//        JasperCompileManager.compileReportToFile(telPath,jasperDatapath);
//
//        JasperPrint jasperPrint = JasperFillManager.fillReport(jasperDatapath, null);
//
//        String filename= UUID.randomUUID().toString().replaceAll("-","")+".pdf";
//        String pdfPath = "D:\\demo\\dow\\"+filename;
//        JasperExportManager.exportReportToPdfFile(jasperPrint, pdfPath);


        Map<String,Object> data=businessService.getData();
        data.put("reportDate",new SimpleDateFormat("yyyy-MM-dd").format(new Date()));


//        HashMap<Object, String> map1 = new HashMap<>();
//        map1.put("name","体检");
//        map1.put("setmeal_count","1000");
//        map1.put("proportion","10%");
//        HashMap<Object, String> map2 = new HashMap<>();
//        map2.put("name","体检1");
//        map2.put("setmeal_count","100");
//        map2.put("proportion","14%");
//
//        ArrayList list = new ArrayList();
//        Collections.addAll(list,map1,map2);
        List list = businessService.getDataList();
        System.out.println(list);

        String telPath="D:\\demo\\tel\\health_business3.jrxml";
        String jasperDatapath="D:\\demo\\tel\\health_business3.jasper";
        JasperCompileManager.compileReportToFile(telPath,jasperDatapath);

        JasperPrint jasperPrint = JasperFillManager.fillReport(jasperDatapath, data,new JRBeanCollectionDataSource(list));


        String filename= UUID.randomUUID().toString().replaceAll("-","")+".pdf";
        String pdfPath = "D:\\demo\\dow\\"+filename;
        JasperExportManager.exportReportToPdfFile(jasperPrint, pdfPath);


        String mimeType = res.getServletContext().getMimeType(filename);
        resp.setHeader("content-type",mimeType);
        resp.setHeader("Access-Control-Expose-Headers","content-disposition");
        resp.setHeader("content-disposition","attachment;filename="+filename);

        FileInputStream fileInputStream = new FileInputStream(pdfPath);
        ServletOutputStream outputStream = resp.getOutputStream();

        int len=-1;
        byte[] bytes=new byte[1024];
        while ((len=fileInputStream.read(bytes))!=-1){
            outputStream.write(bytes,0,len);
        }

        fileInputStream.close();

    }
}
